package code.oldCode.feishuSpecializedTraining.stack_and_queue;

import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Stack;

/**
 * @author 26029
 * @date 2025/3/9
 * @description
 */
public class MyStackQueue {
    // 20. 有效的括号
    public boolean isValid(String s) {
        int len = s.length();
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < len; i++) {
            char c = s.charAt(i);
            if (c == '(' || c == '[' || c == '{') {
                stack.push(c);
            }
            else {
                if (stack.empty())
                    return false;
                char c1 = stack.peek();
                if (c1 == '(' && c == ')' || c1 == '[' && c == ']' || c1 == '{' && c == '}')
                    stack.pop();
                else
                    return false;
            }
        }
        return stack.empty();
    }
}

// 232. 用栈实现队列
class MyQueue {

    Stack<Integer> stackPush;
    Stack<Integer> stackPop;

    public MyQueue() {
        stackPush = new Stack<>();
        stackPop = new Stack<>();
    }

    public void push(int x) {
        stackPush.push(x);
    }

    public int pop() {
        if (stackPop.isEmpty()) {
            while (!stackPush.isEmpty()) {
                stackPop.push(stackPush.pop());
            }
        }
        return stackPop.pop();
    }

    public int peek() {
        if (stackPop.isEmpty()) {
            while (!stackPush.isEmpty()) {
                stackPop.push(stackPush.pop());
            }
        }
        return stackPop.peek();
    }

    public boolean empty() {
        return stackPop.isEmpty() && stackPush.isEmpty();
    }
}

// 225. 用队列实现栈
class MyStack {
    Queue<Integer> queue1;
    Queue<Integer> queue2;
    boolean isOne = false;

    public MyStack() {
        queue1 = new ArrayDeque<>();
        queue2 = new ArrayDeque<>();
    }

    public void push(int x) {
        isOne = !isOne;
        if (isOne) {
            queue1.offer(x);
            while (!queue2.isEmpty()) {
                queue1.offer(queue2.poll());
            }
        } else {
            queue2.offer(x);
            while (!queue1.isEmpty()) {
                queue2.offer(queue1.poll());
            }
        }
    }

    public int pop() {
        if (isOne)
            return queue1.poll();
        else
            return queue2.poll();
    }

    public int top() {
        if (isOne)
            return queue1.peek();
        else
            return queue2.peek();
    }

    public boolean empty() {
        return queue1.isEmpty() && queue2.isEmpty();
    }
}